package com.zhuhjay.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;

import javax.annotation.Nullable;
import java.io.IOException;
import java.lang.reflect.Type;

/**
 * @author ZhuHJay
 * @date 2023/1/13 12:05
 */
@Slf4j
// @ControllerAdvice(basePackages = "com.zhuhjay.controller")
public class GlobalRequestBodyHandler implements RequestBodyAdvice {
    @Override
    public boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        log.info(
                "\nRequestBodyAdvice supports:\n" +
                "\tMethodParameter -> {}\n" +
                "\tType -> {}\n" +
                "\tClass -> {}",
                methodParameter, targetType, converterType
        );
        return true;
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
        log.info(
                "\nRequestBodyAdvice beforeBodyRead:\n" +
                        "\tHttpInputMessage -> {}\n" +
                        "\tMethodParameter -> {}\n" +
                        "\tType -> {}\n" +
                        "\tClass -> {}",
                inputMessage, parameter, targetType, converterType
        );
        return inputMessage;
    }

    @Override
    public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        log.info(
                "\nRequestBodyAdvice afterBodyRead:\n" +
                        "\tObject -> {}\n" +
                        "\tHttpInputMessage -> {}\n" +
                        "\tMethodParameter -> {}\n" +
                        "\tType -> {}\n" +
                        "\tClass -> {}",
                body, inputMessage, parameter, targetType, converterType
        );
        return body;
    }

    @Override
    public Object handleEmptyBody(@Nullable Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        log.info(
                "\nRequestBodyAdvice afterBodyRead:\n" +
                        "\tObject -> {}\n" +
                        "\tHttpInputMessage -> {}\n" +
                        "\tMethodParameter -> {}\n" +
                        "\tType -> {}\n" +
                        "\tClass -> {}",
                body, inputMessage, parameter, targetType, converterType
        );
        return body;
    }
}
